<template>
 <div>
   <div class="m-top">
    <div class="wrap">
      <h1 class="logo">
        <a href="/#">易云音乐</a>
      </h1>
      <ul class="m-nav j-tflag">
        <li class="fst">
          <span @click="chose = 'recommend'">
            <router-link to="/" >
              <a :class="chose === 'recommend' ? 'z-slt' : ''">
                <em>发现音乐</em>
                <sub class="cor">&nbsp;</sub>
              </a>
            </router-link>
          </span>
        </li>
        <li>
          <span @click="linkToMyMusic">
            <!--<router-link to="/">-->
            <a :class="chose === 'myMusic' ? 'z-slt' : ''">
              <em>我的音乐</em>
              <sub class="cor">&nbsp;</sub>
            </a>
            <!--</router-link>-->
          </span>
        </li>
        <li>
          <span @click="chose = 'playlist'"><a :class="chose === 'playlist' ? 'z-slt' : ''"><router-link to="playlist" >
            <em>歌单</em>
          </router-link><sub class="cor">&nbsp;</sub><i class="dot u-icn u-icn-68 f-alpha j-t" style=""></i></a></span>
        </li>
        <li>
          <span @click="chose = 'artist'"><a :class="chose === 'artist' ? 'z-slt' : ''"> <router-link to="artist" >
            <em>歌手</em>
          </router-link><sub class="cor">&nbsp;</sub></a></span>
        </li>
        <li>
          <span><a @click="toArtistHome"><em>音乐人</em></a></span>
        </li>
        <li class="lst">
          <span @click="chose = 'album'"><a :class="chose === 'album' ? 'z-slt' : ''"> <router-link to="album" >
            <em>新碟上架</em>
          </router-link><sub class="cor">&nbsp;</sub></a></span><sup class="hot">&nbsp;</sup>
        </li>
      </ul>

      <el-dropdown class="m-msg-wrap f-pr j-tflag"  @command="handleCommand">
          <span class="el-dropdown-link">
            <a class="m-msg f-pr j-tflag" v-if="messageNum !== 0">
              <el-badge :value="messageNum" class="item" >
                <img :src="changeUrlToResizeImg(userInfo.avatarImgUrl, 30)" style="border-radius: 45%; border: 1px solid lightgrey" height="30px" width="30px"/>
              </el-badge>
            </a>
            <a class="m-msg f-pr j-tflag" v-else>
                <img :src="changeUrlToResizeImg(userInfo.avatarImgUrl, 30)" style="border-radius: 45%; border: 1px solid lightgrey" height="30px" width="30px"/>
            </a>
            <!--<i class="el-icon-arrow-down el-icon--right"></i>-->
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item  :command="item.command" v-for="(item, index) in dropdownMenu">

              <div v-if="item.command === 'message' && messageNum !== 0">
                <el-badge :value="messageNum" class="item" style="margin-top: 5px" >
                  {{item.text}}
                </el-badge>
              </div>
              <div v-else>
                {{item.text}}
              </div>

            </el-dropdown-item>
          </el-dropdown-menu>

      </el-dropdown>

      <el-dialog title="登录" :visible.sync="dialogLoginFormVisible"
                 width="20%"
                 center>
        <el-form :model="loginForm" :rules="loginRules" ref="loginForm" label-width="0px" >
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="用户名"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" placeholder="密码" v-model="loginForm.password" @keyup.enter.native="submitLoginForm"></el-input>
          </el-form-item>
          <Verify v-if="hackReset" @success="alertVerify('success')" @error="alertVerify('error')" :type="3" :barSize="verifybarSize"></Verify>
        </el-form>
        <!--<el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>-->
        <span slot="footer" class="dialog-footer">
           <el-button @click="dialogLoginFormVisible = false">取 消</el-button>
           <el-button type="primary" @click="submitLoginForm" :disabled="loginDisabled">登 录</el-button>
        </span>
      </el-dialog>

      <el-dialog title="注册" :visible.sync="dialogRegisterFormVisible"
                 width="20%"
                 center>
        <el-form :model="registerForm" :rules="registerRules" ref="registerForm" label-width="0px" >
          <el-form-item prop="username">
            <el-input v-model="registerForm.username" placeholder="用户名"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" placeholder="输入密码" v-model="registerForm.password"></el-input>
          </el-form-item>
          <el-form-item prop="passwordForCheck">
            <el-input type="password" placeholder="确认密码" v-model="registerForm.passwordForCheck" @keyup.enter.native="submitRegisterForm"></el-input>
          </el-form-item>
        </el-form>
        <!--<el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>-->
        <span slot="footer" class="dialog-footer">
           <el-button @click="dialogRegisterFormVisible = false">取 消</el-button>
           <el-button type="primary" @click="submitRegisterForm">注 册</el-button>
        </span>
      </el-dialog>

      <!--<a class="m-msg f-pr j-tflag" href="/msg/#/private">-->
        <!--<i class="bub u-bub ">-->
        <!--</i>-->
      <!--</a>-->


      <div class="m-srch f-pr j-suggest" id="g_search">
          <div class="srchbg">
              <span class="parent">
              <input type="text" class="txt j-flag" style="opacity: 1;"  v-model="searchQuery" v-on:input="inputQuery" @keyup.enter="toSearch">
              </span>

        </div>
      </div>
    </div>
  </div>
  <div class="m-subnav m-subnav-up f-pr j-tflag" v-if='isSubNav'>
    <div class="shadow">&nbsp;</div>
  </div>
  <div class="m-subnav j-tflag" v-else>
    <div class="wrap f-pr">
      <ul class="nav">
        <li><a><em>推荐</em></a></li>
        <li><a><em>排行榜</em></a></li>
        <li>
          <router-link to="playlist" @click='isSubNav=false'>
            <em>歌单</em>
          </router-link>
        </li>
        <li><a><em>主播电台</em></a></li>
        <!--<li><a><em>歌手</em></a></li>-->
        <li>
          <router-link to="artist" @click='isSubNav=false'>
            <em>歌手</em>
          </router-link>
        </li>
        <li><a><em>新碟上架</em></a></li>
      </ul>
    </div>
  </div>
</div>

</template>

<script>


  import {userDetail, login, logout, searchAll, apiContext} from "./../service/getData"
  import {getUser, setUser, clearUser} from  './../util/userUtils';
  import Verify from 'vue2-verify'
  import Bus from '../util/bus';

  export default {
    name: 'top',
    data () {
      const checkName = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('用户名不能为空'));
        }

        this.$http.post(apiContext+"user/verifyName", {
          nickname: value
        }, {
          emulateJSON : true
        }).then(res => {
          console.log(res);
          let status = res.body.status;
          if (status === 200) {
            this.$message({
              message: '该用户名可以使用',
              type: 'success'
            });
            callback();
          } else {
            // this.$message({
            //   message: res.body.msg,
            //   type: 'error'
            // });
            callback(new Error(res.body.msg));
          }
        })
      };
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.registerForm.passwordForCheck !== '') {
            this.$refs.registerForm.validateField('passwordForCheck');
          }
          callback();
        }
      };
      const validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.registerForm.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        searchSuggests: [],
        inputValue: "",
        searchQuery: "",
        messageNum: 0,
        chose: "recommend",
        userInfo: {
          name: "",
          description: "",
          avatarImgUrl: "http://p1.music.126.net/VnZiScyynLG7atLIZ2YPkw==/18686200114669622.jpg?param=30y30",
          numberOfFollow: 0,
          numberOfFollower: 0
        },
        userInfoDefault: {
          name: "",
          description: "",
          avatarImgUrl: "http://p1.music.126.net/VnZiScyynLG7atLIZ2YPkw==/18686200114669622.jpg?param=30y30",
          numberOfFollow: 0,
          numberOfFollower: 0
        },
        hackReset: true,
        loginDisabled: true,
        verifybarSize: {
          width: '100%',
          height: '40px'
        },
        msg: 'this is the header of demo',
        isSubNav: true,
        dialogLoginFormVisible: false,
        dialogRegisterFormVisible: false,
        loginForm: {
          username: "",
          password: ""
        },
        registerForm: {
          username: "",
          password: "",
          passwordForCheck: ""
        },
        dropdownMenu: {},
        menuNotLogin: [
          {command: "login", text: "登录"},
          {command: "register", text: "注册"}
          ],
        menuLogined: [
          {command: "myhome", text: "我的主页"},
          {command: "message", text: "我的消息"},
          {command: "setting", text: "个人设置"},
          {command: "logout", text: "退出"}
          ],
        loginRules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ],
        },
        registerRules: {
          username: [
            { validator: checkName, trigger: 'blur' }
          ],
          password: [
            { validator: validatePass, trigger: 'blur' }
          ],
          passwordForCheck: [
            { validator: validatePass2, trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      toArtistHome() {
        let user = getUser();
        if (user === null) {
          this.$message.info("请先登录");
          return ;
        }
        if (user.artistId === null || user.artistId === undefined) {
          this.$message.info("您还不是音乐人");
          return ;
        }
        this.$router.push({ path: '/myAlbum' })
      },
      inputQuery() {
        console.log(this.searchQuery)
      },
      toSearch() {
        this.$router.push({ path: '/searchResult', query:{searchQuery:this.searchQuery} })
      },
      querySearchAsync(queryString, cb) {

        searchAll(this).get({
          pageNum: 0,
          pageSize: 3,
          query: queryString
        }).then(res => {
          console.log(res)
          let data = res.body.data;
          let albums = data.albumPage.content;
          albums.forEach(function (item) {
            item['searchType'] = "专辑"
          })
          let artists = data.artistPage.content;
          artists.forEach(function (item) {
            item['searchType'] = "歌手"
          })
          let playlists = data.playlistPage.content;
          playlists.forEach(function (item) {
            item['searchType'] = "歌单"
          })
          let songs = data.songPage.content;
          songs.forEach(function (item) {
            item['searchType'] = "单曲"
          })
          this.searchSuggests = []
          this.searchSuggests = this.searchSuggests.concat(songs)
          this.searchSuggests = this.searchSuggests.concat(playlists)
          this.searchSuggests = this.searchSuggests.concat(albums)
          this.searchSuggests = this.searchSuggests.concat(artists)

          console.log(this.searchSuggests)

          cb(this.searchSuggests);
        })

      },
      handleSelectForSearch(item) {
        console.log(item);
        this.searchQuery = item.name;
      },
      changeUrlToResizeImg(picUrl, size) {
        if (picUrl.indexOf("yunmusic_dev") === -1) {
          return picUrl;
        }
        return picUrl.replace(/yunmusic_dev/, "resize_" + size + 'x' + size);
      },
      linkToMyMusic() {
        if (getUser() === null) {
          this.dialogLoginFormVisible = true;
        } else {
          // location.reload();
          this.$router.push({ path: '/myMusic'});
          this.chose = "myMusic"
          this.isSubNav = true;
        }
      },
      handleCommand(command) {
        if (command === "login") {
          this.dialogLoginFormVisible = true;
        } else if (command === 'register'){
          this.dialogRegisterFormVisible = true;
        } else if (command === 'logout') {
          this.requestLogout()
        } else if (command === 'message') {
          console.log(getUser())
          this.$router.push({ path: '/myMessages'})
        } else if (command === "myhome") {
          if (getUser() === null) {
            this.dialogLoginFormVisible = true;
          } else {
            this.$router.push({ path: '/myHome'})
          }
        } else if (command === 'setting') {
          if (getUser() === null) {
            this.dialogLoginFormVisible = true;
          } else {
            this.$router.push({ path: '/userSetting'})
          }
        }
        // this.$message('click on item ' + command);
      },
      requestLogout() {
        let user = getUser();
        if (user === null) {
          return ;
        }
        let userId = user['id']
        let userToken = user['userToken']

        this.$http.post(apiContext+"logout", {
          userId: userId
        }, {
          emulateJSON : true,
          headers: {
            'Content-Type': 'x-www-form-urlencoded',
            'userId': userId,
            'userToken': userToken
          }}).then(res => {
          console.log(res);
          let status = res.body.status;
          if (status === 200) {
            location.reload();
            this.$message({
              message: '退出成功',
              type: 'success'
            });

          } else {
            this.$message({
              message: res.body.msg,
              type: 'error'
            });
          }
        })
        clearUser();
        this.dropdownMenu = this.menuNotLogin
      },
      submitLoginForm() {
        this.$refs["loginForm"].validate((valid) => {
          if (valid) {
              this.$http.post(apiContext+"login", {
                nickname: this.loginForm.username,
                password: this.loginForm.password
              }, {emulateJSON : true})
              .then((res) => {
                console.log(res);
                let status = res.body.status;
                if (status === 200) {
                  let user = res.body.data;
                  setUser(user);
                  this.userInfo = user;
                  this.$message({
                    message: '登陆成功',
                    type: 'success'
                  });
                  Bus.$emit("refresh-user", user);
                  this.dialogLoginFormVisible = false;
                  this.dropdownMenu = this.menuLogined;
                  this.loginDisabled = true;

                  // 发送给websocketWorker
                  Bus.$emit('on-websocket-open', user)

                } else {
                  this.$message({
                    message: res.body.msg,
                    type: 'error'
                  })
                  this.loginDisabled = true;
                }
              });
          } else {
            console.log('error submit!!');
            return false;
          }
          // 强制验证码刷新
          this.hackReset = false
          this.$nextTick(() => {
            this.hackReset = true
          })

        });

      },
      submitRegisterForm() {
        this.$refs["registerForm"].validate((valid) => {
          if (valid) {
            this.$http.post(apiContext+"user/register", {
              nickname: this.registerForm.username,
              password: this.registerForm.password
            }, {emulateJSON : true})
              .then((res) => {
                console.log(res);
                let status = res.body.status;
                if (status === 200) {

                  this.$message({
                    message: '注册成功',
                    type: 'success'
                  });
                  this.dialogRegisterFormVisible = false;
                } else {
                  this.$message({
                    message: res.body.msg,
                    type: 'error'
                  })
                  this.loginDisabled = true;
                }
              });

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      isLogined() {
        return getUser() !== null;
      },
      alertVerify(message) {
        if (message === 'success') {
          this.loginDisabled = false;
          this.$message({
            message: '验证成功',
            type: 'success'
          });
        } else {
          this.$message({
            message: '验证失败',
            type: 'error'
          });
        }
      },
      checkToken() {
        if (getUser() !== null) {
          let user = getUser();
          if (user.userToken === '' || user.userToken === undefined || user.userToken === null ) {
            clearUser();
            Bus.$emit("refresh-user", user);
            return ;
          }
          this.userInfo = user;
          let _this = this;

          this.$http.post(apiContext + "checkToken", {}, {
            emulateJSON: true,
            headers: {
              'Content-Type': 'x-www-form-urlencoded',
              'userId': user.id,
              'userToken': user.userToken
            }
          }).then(res => {
            console.log(res);
            if (res.body.status !== 200) {
              clearUser();
              this.userInfo = this.userInfoDefault;
              this.dropdownMenu = this.menuNotLogin;
              Bus.$emit("refresh-user", user);
            } else {
              this.dropdownMenu = this.menuLogined;
              // 发送给websocketWorker
              Bus.$emit('on-websocket-open', user)
              Bus.$emit("refresh-user", user);
            }
          }).catch(res => {
            console.log(res)
            this.$message({
              message: '账号已在异地登录了，请重新登录',
              type: 'info'
            });
            clearUser();
            this.userInfo = this.userInfoDefault;
            this.dropdownMenu = this.menuNotLogin;
            Bus.$emit("refresh-user", user);
          })
        } else {
          this.dropdownMenu = this.menuNotLogin;
        }
      },
      refreshUser() {
        let user = getUser();
        userDetail(this).get({
          userId: user['id']
        }).then(res => {
          console.log(res)
          let status = res.body.status;
          if (status === 200) {
            let data = res.body.data;

            this.userInfo = data;
            data.userToken = user.userToken;
            setUser(data)

            this.isArtist = (data.artistId !== null && data.artistId !== undefined)
          }
        })
      },
    },
    mounted() {
      // this.dropdownMenu = this.menuLogined;
      this.checkToken();

      let _this = this;
      Bus.$on("update-messageNum", function (data) {
        _this.messageNum = data.notReadCommentNum;
        if (_this.messageNum > 0) {
          _this.$notify.info({
            title: '消息',
            message: '您收到了' + String(_this.messageNum)  + '条消息',
          });
        }
      })

      Bus.$on("is-artist", function (data) {
        let user = getUser();
        user.artistId = data.artistId;
        setUser(user);
      });

      Bus.$on("refresh-user-info", function () {
        _this.refreshUser();
      })
    },
    components: {
      Verify
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .m-top{
    height: 70px;
    background-position: 0 -80px;
    background-repeat: repeat-x;
  }
  .wrap{
    width:1100px;
    margin:0 auto;
  }
  .m-top .logo {
    float: left;
    width: 176px;
  }
  .m-top .logo a {
    float: left;
    width: 107px;
    height: 33px;
    padding: 22px 20px 0 0;
    background-position: -60px 15px;
    text-indent: -9999px;
  }
  .m-nav {
    float: left;
  }
  .m-nav li {
    position: relative;
    background-position: right -300px;
  }
  .m-nav li, .m-nav li span, .m-nav a, .m-nav a em {
    float: left;
    height: 70px;
    font-size: 14px;
  }
  .m-nav a {
    position: relative;
    padding-left: 2px;
    text-align: center;
    line-height: 76px;
  }
  .m-nav a em {
    padding: 0 20px 0 18px;
    overflow: hidden;
    color: #ccc;
    text-shadow: 0 1px 0 #1b1b1b;
    cursor: pointer;
  }
  .m-nav a.z-slt {
    position: relative;
    margin: 0 -1px;
    background-position: left -155px;
  }
  .m-nav a.z-slt em {
    padding: 0 21px 0 19px;
    background-position: right -155px;
  }
  .m-nav .cor {
    display: none;
  }
  .m-nav a.z-slt .cor {
    display: block;
    position: absolute;
    left: 50%;
    top: 63px;
    width: 14px;
    height: 9px;
    margin-left: -7px;
    overflow: hidden;
    background-position: -226px 0;
  }
  .m-msg {
    position: relative;
    float: right;
    width: 34px;
    height: 28px;
    margin: 21px 0 0 20px;
    /*background-position: 0 -49px;*/
  }
  .m-msg-wrap {
    position: relative;
    float: right;
    top: 0;
    right: 0;
  }
  .m-msg .bub {
    position: absolute;
    top: 0;
    right: 0;
  }
  .u-bub {
    display: block;
    position: relative;
    zoom: 1;
    width: 22px;
    height: 22px;
    color: #fff;
    text-align: center;
    line-height: 23px;
    font-weight: bold;
  }
  .m-srch .srchbg {
    margin-top: 21px;
    background-position: 0 -550px;
  }
  .m-srch, .m-srch .srchbg {
    float: right;
    width: 210px;
    height: 31px;
  }
  .m-srch .parent {
    display: block;
    position: relative;
    margin: 8px 0 0 33px;
  }
  .m-srch .parent input {
    width: 90%;
    margin: 0;
    padding: 0;
    background: transparent;
    color: #fff;
    outline: none;
  }
  .m-srch .parent input {
    color: #333;
  }
  .m-subnav {
    z-index: 90;
    height: 35px;
    background-position: 0 -230px;
    background-repeat: repeat-x;
  }
  .m-subnav-up {
    height: 5px;
    overflow: hidden;
  }
  .m-subnav .wrap {
    width: 911px;
    padding-left: 168px;
    margin: 0 auto;
  }
  .f-pr {
    position: relative;
    zoom: 1;
  }
  .m-subnav .nav li {
    display: inline;
    margin: 0 17px;
  }
  .m-subnav .nav li, .m-subnav .nav a, .m-subnav .nav em {
    float: left;
    height: 35px;
    overflow: hidden;
  }
  .m-subnav .nav li, .m-subnav .nav a, .m-subnav .nav em {
    float: left;
    height: 35px;
    overflow: hidden;
  }
  .m-subnav .nav a {
    padding-left: 14px;
  }
  .m-subnav .nav a:hover, .m-subnav .nav a.z-slt {
    background-position: left -268px;
  }
  .m-subnav .nav li, .m-subnav .nav a, .m-subnav .nav em {
    float: left;
    height: 35px;
    overflow: hidden;
  }
  .m-subnav .nav em {
    padding-right: 14px;
    line-height: 37px;
    color: #fff;
    text-shadow: 0 1px 0 #650303;
  }
  .m-subnav .nav a:hover em, .m-subnav .nav a.z-slt em {
    background-position: right -268px;
  }

  .login-form{

  }


  .el-input__inner {

  }
</style>
